package cn.mrlong.circularprogressdialog;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

public class CircularProgressDialog extends ProgressDialog {
    private TextView hintText;
    private String hintStr = "加载中...";
    private TextView cancel;
    private CancelOnClickListener cancelOnClickListener;

    public interface CancelOnClickListener {
        void cancel();
    }

    public CircularProgressDialog(Context context) {
        super(context, R.style.loadingDialogStyle);
    }

    public CircularProgressDialog(Context context, CancelOnClickListener cancelOnClickListener) {
        super(context, R.style.loadingDialogStyle);
        this.cancelOnClickListener = cancelOnClickListener;
    }

    public CircularProgressDialog setHintText(String msg) {
        this.hintStr = msg;
        return this;
    }

    public CircularProgressDialog setBackBtnCancelable(boolean cancel) {
        this.setCancelable(cancel);
        return this;
    }

    public CircularProgressDialog setOnTouchOutsideCancelable(boolean cancel) {
        this.setCanceledOnTouchOutside(cancel);
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_loading);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.dimAmount = 0.5f;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.CENTER;
        getWindow().setAttributes(params);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        cancel = (TextView) findViewById(R.id.tv_cancel);
        if (null != cancelOnClickListener && null != cancel) {
            cancel.setVisibility(View.VISIBLE);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cancelOnClickListener.cancel();
                    CircularProgressDialog.this.dismiss();
                }
            });
        }
        hintText = (TextView) findViewById(R.id.tv_hint);
        hintText.setText(hintStr);
        hintText.setVisibility(View.VISIBLE);
        //        this.setOnCancelListener(new OnCancelListener() {
        //            @Override
        //            public void onCancel(DialogInterface dialog) {
        //                if (null != cancelOnClickListener) {
        //                    cancelOnClickListener.cancel();
        //                }
        //            }
        //        });
        //this.setCanceledOnTouchOutside(false);
    }

}
